package com.whitecat.voting.security;

import com.whitecat.voting.entity.MpUserInfo;
import com.whitecat.voting.exception.BusinessException;
import com.whitecat.voting.service.MpUserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;

@Slf4j
public class WxCodeRealm extends AuthorizingRealm {

    @Resource
    private MpUserInfoService mpUserInfoService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof WxCodeToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String openId = (String) token.getPrincipal();
        if (openId == null) {
            throw new BusinessException("openid不能为空！");
        }

        MpUserInfo mui = mpUserInfoService.findById(openId);
        if (mui == null) {
            throw new BusinessException("账号不存在！");
        }

        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        session.setAttribute("mpUserInfo", mui);

        return new SimpleAuthenticationInfo(
                openId,
                openId,
                getName()
        );
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
}
